package com.sanjiahantang.youjiarole.module.common.views.impl;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.article.views.impl.ArticleListActivity;
import com.sanjiahantang.youjiarole.module.cases.beans.CaseBean;
import com.sanjiahantang.youjiarole.module.cases.views.CaseView;
import com.sanjiahantang.youjiarole.module.common.presenters.SearchPresenter;
import com.sanjiahantang.youjiarole.module.goods.views.impl.GoodsListActivity;
import com.sanjiahantang.youjiarole.utils.KeyBoardUtils;
import com.sanjiahantang.youjiarole.utils.SPUtils;

import java.util.List;

/**
 * Created by zy on 2017/10/16.
 */

public class SearchActivity extends BaseMvpActivity<BaseView, SearchPresenter> implements BaseView, View.OnClickListener {


    private View btnClearHistory;
    private QuickAdapter<CaseBean.Item> caseAdapter;
    private EditText cetSearch;
    private ListView lvHistory;
    private ImageView seach_back;
    private String currentHistoryKey;

    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    @Override
    public SearchPresenter initPresenter() {
        return new SearchPresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_search);
        btnClearHistory = findViewById(R.id.btnClearHistory);
        cetSearch = (EditText) findViewById(R.id.cetSearch);
        findViewById(R.id.iv_back).setOnClickListener(this);
        lvHistory = (ListView) findViewById(R.id.lvHistory);
        int type = getIntent().getIntExtra(KEY_TYPE, 0);
        switch (type) {
            case SEARCH_TYPE_CASE:
                currentHistoryKey = SPConfig.SEARCH_HISTORY_KEY_CASE;
                loadLocalCaseList();
                break;
            case SEARCH_TYPE_HELP:
                loadHelpList();
                break;
            case SEARCH_TYPE_GOODS:
                currentHistoryKey = SPConfig.SEARCH_HISTORY_KEY_GOODS;
                loadLocalGoodsList();
                break;
            case SEARCH_TYPE_ARTICLE_TYPE:
                loadList(SPConfig.SEARCH_HISTORY_KEY_ARTICLE_TYPE, ArticleListActivity.class);
                break;
            case SEARCH_TYPE_ARTICLE:
                loadList(SPConfig.SEARCH_HISTORY_KEY_ARTICLE,null);
                break;
            case SEARCH_TYPE_CUSTOMER:
                loadList(SPConfig.SEARCH_HISTORY_KEY_CUSTOMER,null);
                break;
            case SEARCH_TYPE_PARTNER:
                loadList(SPConfig.SEARCH_HISTORY_KEY_PARTNER,null);
                break;
            case SEARCH_TYPE_INCREASE:
                loadList(SPConfig.SEARCH_HISTORY_KEY_INCREASE,null);
                break;
            case SEARCH_TYPE_GOODS_FROM_LIST:
                loadList(SPConfig.SEARCH_HISTORY_KEY_GOODS,null);
                break;
            case SEARCH_TYPE_ACCOUNT:
                cetSearch.setHint("搜索订单号或项目名称");
                loadList(SPConfig.SEARCH_HISTORY_KEY_ACCOUNT,null);
                break;
        }
        findViewById(R.id.btnCancel).setOnClickListener(this);
    }

    private void loadList(final String key, final Class toClass) {
        btnClearHistory.setOnClickListener(this);
        currentHistoryKey = key;
        String json = SPUtils.get($this, key, "[]").toString();
        List<CaseBean.Item> itemList = new Gson().fromJson(json, new TypeToken<List<CaseBean.Item>>() {
        }.getType());
        if (itemList == null || itemList.size() == 0) {
            btnClearHistory.setVisibility(View.GONE);
        } else {
            btnClearHistory.setVisibility(View.VISIBLE);
            caseAdapter = new QuickAdapter<CaseBean.Item>($this, R.layout.item_text, itemList) {
                @Override
                protected void convert(BaseAdapterHelper helper, final CaseBean.Item item) {
                    helper.setText(R.id.text1, item.getResidentialName());
                    helper.getView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            setSearchResult(item.getResidentialName(),toClass);
                        }

                    });
                }
            };
            lvHistory.setAdapter(caseAdapter);
        }

        cetSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains("\n")) {
                    String keyWords = charSequence.toString().substring(0, charSequence.toString().length() - 1);
                    setSearchResult(keyWords,toClass);
                    if (!TextUtils.isEmpty(keyWords)) {
                        String json = SPUtils.get($this, key, "[]").toString();
                        Gson gson = new Gson();
                        List<CaseBean.Item> itemList = gson.fromJson(json, new TypeToken<List<CaseBean.Item>>() {
                        }.getType());
                        CaseBean.Item item = new CaseBean.Item();
                        item.setResidentialName(keyWords);
                        itemList.add(item);
                        SPUtils.put($this, key, gson.toJson(itemList));
                    }

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void loadLocalGoodsList() {
        btnClearHistory.setOnClickListener(this);
        String json = SPUtils.get($this, SPConfig.SEARCH_HISTORY_KEY_GOODS, "[]").toString();
        List<CaseBean.Item> itemList = new Gson().fromJson(json, new TypeToken<List<CaseBean.Item>>() {
        }.getType());
        if (itemList == null || itemList.size() == 0) {
            btnClearHistory.setVisibility(View.GONE);
        } else {
            btnClearHistory.setVisibility(View.VISIBLE);
            caseAdapter = new QuickAdapter<CaseBean.Item>($this, R.layout.item_text, itemList) {
                @Override
                protected void convert(BaseAdapterHelper helper, final CaseBean.Item item) {
                    helper.setText(R.id.text1, item.getResidentialName());
                    helper.getView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            goGoodsListPage(item.getResidentialName());
                        }

                    });
                }
            };
            lvHistory.setAdapter(caseAdapter);
        }

        cetSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains("\n")) {
                    String keyWords = charSequence.toString().substring(0, charSequence.toString().length() - 1);
                    setCaseResult(keyWords);
                    if (!TextUtils.isEmpty(keyWords)) {
                        saveGoods(keyWords);
                    }
                    goGoodsListPage(keyWords);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void saveGoods(String keyWords) {
        String json = SPUtils.get($this, SPConfig.SEARCH_HISTORY_KEY_GOODS, "[]").toString();
        Gson gson = new Gson();
        List<CaseBean.Item> itemList = gson.fromJson(json, new TypeToken<List<CaseBean.Item>>() {
        }.getType());
        CaseBean.Item item = new CaseBean.Item();
        item.setResidentialName(keyWords);
        itemList.add(item);
        SPUtils.put($this, SPConfig.SEARCH_HISTORY_KEY_GOODS, gson.toJson(itemList));
    }

    private void loadHelpList() {
        cetSearch.setHint(R.string.key_words_help_hint);
        presenter.initAdapter($this, lvHistory);
        presenter.loadHelpList($this, "");
        cetSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains("\n")) {
                    String keyWords = charSequence.toString().substring(0, charSequence.toString().length() - 1);
                    presenter.loadHelpList($this, keyWords);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void loadLocalCaseList() {
        btnClearHistory.setOnClickListener(this);
        String json = SPUtils.get($this, SPConfig.SEARCH_HISTORY_KEY_CASE, "[]").toString();
        List<CaseBean.Item> itemList = new Gson().fromJson(json, new TypeToken<List<CaseBean.Item>>() {
        }.getType());
        if (itemList == null || itemList.size() == 0) {
            btnClearHistory.setVisibility(View.GONE);
        } else {
            btnClearHistory.setVisibility(View.VISIBLE);
            caseAdapter = new QuickAdapter<CaseBean.Item>($this, R.layout.item_text, itemList) {
                @Override
                protected void convert(BaseAdapterHelper helper, final CaseBean.Item item) {
                    helper.setText(R.id.text1, item.getResidentialName());
                    helper.getView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            setCaseResult(item.getResidentialName());
                        }

                    });
                }
            };
            lvHistory.setAdapter(caseAdapter);
        }

        cetSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains("\n")) {
                    String keyWords = charSequence.toString().substring(0, charSequence.toString().length() - 1);
                    setCaseResult(keyWords);
                    if (!TextUtils.isEmpty(keyWords)) {
                        saveCase(keyWords);
                    }

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    public void initData() {

    }

    private void setSearchResult(String keyword,Class toClass){
        if(toClass == null){
            Intent intent = new Intent();
            intent.putExtra(KEY_KEYWORDS, keyword);
            setResult(RESULT_OK, intent);
            finish();
        }else{
            Intent intent = new Intent($this,toClass);
            intent.putExtra(KEY_KEYWORDS, keyword);
            startActivity(intent);
            finish();
        }
        KeyBoardUtils.closeKeybord($this);
    }

    private void goGoodsListPage(String keywords) {
        Intent intent = new Intent($this, GoodsListActivity.class);
        intent.putExtra(KEY_KEYWORDS, keywords);
        startActivity(intent);
        finish();
    }

    private void setCaseResult(String keyWords) {
        Intent intent = new Intent();
        intent.putExtra(CaseView.KEY_CASE_TITLE, keyWords);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void saveCase(String keyWords) {
        String json = SPUtils.get($this, SPConfig.SEARCH_HISTORY_KEY_CASE, "[]").toString();
        Gson gson = new Gson();
        List<CaseBean.Item> itemList = gson.fromJson(json, new TypeToken<List<CaseBean.Item>>() {
        }.getType());
        CaseBean.Item item = new CaseBean.Item();
        item.setResidentialName(keyWords);
        itemList.add(item);
        SPUtils.put($this, SPConfig.SEARCH_HISTORY_KEY_CASE, gson.toJson(itemList));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnCancel:
                setResult(RESULT_CANCELED);
                finish();
                break;
            case R.id.btnClearHistory:
                SPUtils.put($this, currentHistoryKey, "[]");
                caseAdapter.clear();
                btnClearHistory.setVisibility(View.GONE);
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }
}
